package help_request

import (
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/help_request"
	ServiceAdmin "gq_volunteer_platform/service/admin"

	"github.com/gin-gonic/gin"
)

func MyList(c *gin.Context) {
	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		Title          string `binding:"max=255"`
		Status         string `binding:"oneof='' 处理中 已驳回 已完结"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, req.OrganizationId)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 查询
	var count int64
	var list []help_request.HelpRequest
	var tx = bean.MysqlDb.Model(&help_request.HelpRequest{})

	tx.Where("`organization_id` in ?", organization_my_ids)

	if req.Title != "" {
		tx = tx.Where("`title` like ?", "%"+req.Title+"%")
	}
	if req.Status != "" {
		tx = tx.Where("`status`=?", req.Status)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func Read(c *gin.Context) {
	var req struct {
		ID     uint   `binding:"max=10000000"`
		Status string `binding:"oneof=未读 已读"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one help_request.HelpRequest
	one.ID = req.ID
	one.Status = req.Status

	if err := bean.MysqlDb.Updates(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
}
